﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using GMS.Dinasty.BO;
using System.Data;
using System.Windows.Forms;

namespace GMS.Dinasty.DAL
{
    class DataAccessUser
    {
        public SqlDataReader Test()
        {
            string cs = "server=pavel;uid=pavel;pwd=123456;database=GMSDatabase";
            SqlConnection conn = new SqlConnection(cs);
            SqlCommand selectContact = new SqlCommand("DSelectUserByLogin 'current'", conn);
            conn.Open();
            SqlDataReader reader = selectContact.ExecuteReader();
            reader.Read();
            return reader;
        }

        public List<User> SelectUsers(string Connectionstring, string StoreProcedures)
        {
            SqlConnection connection = new SqlConnection();
            SqlCommand selectUsers = new SqlCommand();
            selectUsers.CommandType = CommandType.StoredProcedure;
            selectUsers.CommandText = StoreProcedures;
            selectUsers.Connection = connection;
            connection.ConnectionString = Connectionstring;
            List<User> listUsers = new List<User>();

            try
            {
                connection.Open();
                SqlDataReader Reader = selectUsers.ExecuteReader();
                while (Reader.Read())
                {
                    listUsers.Add(CreateUser(Reader));
                }
            }
            catch (SqlException exception)
            {
                MessageBox.Show(exception.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                connection.Close();
            }
            return listUsers;
        }
        public User CreateUser(SqlDataReader reader)
        {
            User user = new User(reader.GetInt32(reader.GetOrdinal("IdUser")));
            user.Name = reader.GetString(reader.GetOrdinal("Name"));
            user.SName = reader.GetString(reader.GetOrdinal("SName"));
            user.TName = reader.GetString(reader.GetOrdinal("TName"));
            user.Login = reader.GetString(reader.GetOrdinal("Login"));
            return user;
        }
    }
}
